package com.select.course.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.select.course.entity.*;
import com.select.course.mapper.AdminMapper;
import com.select.course.service.*;
import com.select.course.utils.JwtUtil;
import com.select.course.utils.R;
import com.select.course.vo.AdminVo;
import com.select.course.vo.SumarizeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 24820
 * @description 针对表【c_user_admin】的数据库操作Service实现
 * @createDate 2022-10-25 17:40:23
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin>
        implements AdminService {
    //    public static ThreadLocal<LoginUser> toThreadLocal = new ThreadLocal<>();
    @Resource
    private UserStudentService userStudentService;
    @Resource
    private UserTeacherService userTeacherService;
    @Resource
    private SchoolCollegeService schoolCollegeService;
    @Resource
    private SchoolMajorService schoolMajorService;
    @Resource
    private SchoolClassService schoolClassService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public R loginAdmin(AdminVo adminVo) {
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                new UsernamePasswordAuthenticationToken(adminVo.getUserId(), adminVo.getPassword());

        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
//        Admin id_number = this.getOne(new QueryWrapper<Admin>().eq("id_number", adminVo.getUserId()));
//        BCryptPasswordEncoder encoderPassword = new BCryptPasswordEncoder();
//        String encode = encoderPassword.encode(adminVo.getPassword());
//        if (id_number == null) {
//            return R.error(102, "用户不存在");
//        } else if (id_number.getPassword().equals(adminVo.getPassword())) {
//            return R.ok().put("data", id_number);
//        }
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("账号错误！");
        }
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        if (!loginUser.getPermissions().get(0).toString().equals("ROLE_root")) {
            throw new RuntimeException("账号错误！");
        }
        String jwt = JwtUtil.createJWT(loginUser.getUser().getIdNumber());
        Map<String, Object> map = new HashMap<>();
        map.put("authentication", jwt);
        map.put("username", loginUser.getUser().getUserName());

        // 接下来可将jwt存储于Redis或数据库中，方便下次前端发送请求对比jwt,这里我选择存储在当前线程里面
//        toThreadLocal.set(loginUser);
//        LoginUser instance = LoginUser.getInstance();
//        instance = loginUser;
//        LoginUser loginUser1 = toThreadLocal.get();
//        System.out.println(loginUser1+"+++ThreadId"+Thread.currentThread().getId());

        return R.ok(map);
    }

    @Override
    public SumarizeVo getAdminGetNums() {

        List<SchoolCollege> schoolCollegeList = schoolCollegeService.list();
        List<HashMap<String, String>> hashMapList = schoolCollegeList.stream().map(e -> {
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("collegename", e.getName());
            Long studentCount = userStudentService.count(new QueryWrapper<UserStudent>().eq("college_id", e.getId()));
            hashMap.put("学生人数", String.valueOf(studentCount));
            Long teacherCount = userTeacherService.count(new QueryWrapper<UserTeacher>().eq("college_id", e.getId()));
            hashMap.put("教师人数", String.valueOf(teacherCount));
            return hashMap;
        }).collect(Collectors.toList());
        SumarizeVo sumarizeVo = new SumarizeVo();
        sumarizeVo.setChartValue(hashMapList);
        return sumarizeVo;
    }

    @Override
    public AdminVo getSelf(String userId) {
        Admin id_number = this.getOne(new QueryWrapper<Admin>().eq("id_number", userId));
        AdminVo adminVo = new AdminVo();
        adminVo.setAdminName(id_number.getAdminName());
        adminVo.setPassword(id_number.getPassword());
        adminVo.setUserId(id_number.getIdNumber());
        adminVo.setRegisterTime(id_number.getRegisterTime());
        adminVo.setId(id_number.getId());
        return adminVo;
    }

    @Override
    public R updateSelf(AdminVo adminVo) {
        Admin admin = new Admin();
        admin.setAdminName(adminVo.getAdminName());
        admin.setId(adminVo.getId());
        boolean b = this.updateById(admin);
        if (b) {
            return R.ok().put("data", adminVo);
        }
        return R.error(101,"信息修改错误，请联系管理员！");
    }

    @Override
    public R updatePwd(AdminVo adminVo) {
        Admin admin = new Admin();
        admin.setPassword(adminVo.getPassword());
        admin.setId(adminVo.getId());
        boolean b = this.updateById(admin);
        if (b) {
            return R.ok();
        }
        return R.error(101,"密码修改错误，请联系管理员！");
    }

}




